package com.itbac.springsecurityoauth2demo.service;

import com.itbac.springsecurityoauth2demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 自定义用户登录认证逻辑
 * @author: BacHe
 * @email: 1218585258@qq.com
 * @Date: 2021/3/27 11:05
 */
@Service
public class SecurityUserService implements UserDetailsService{

    //加密前加盐
    private static String salt = "itbac";

    //加密器
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //自定义查询用户。不存在则抛异常
        if (!"bac".equals(username)) {
            throw new UsernameNotFoundException(String.format("username:{%s}不存在", username));
        }

        //对 123 进行加密 ，想加盐，自己加
        String encode = passwordEncoder.encode("123"+salt);

        //查询到的用户名、密码、权限，封装一个User对象返回。
        return new User().setUsername("bac").setPassword(encode).setAuthorities(
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin")
        );
    }
}
